package com.sinosoft.yuebao.servicebus.util;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipayOpenOperationOpenbizmockBizQueryRequest;
import com.alipay.api.response.AlipayOpenOperationOpenbizmockBizQueryResponse;
import com.sinosoft.kuafu.core.util.BeanUtil;
import com.sinosoft.yuebao.servicebus.dto.common.YueBaoRequest;
import com.sinosoft.yuebao.servicebus.dto.common.YueBaoResponse;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyPair;
import java.util.*;

/**
 * 悦保utils
 * @author handong
 */
public class YueBaoUtils {


    /**
     * 获取加密串
     * @param sortedParams
     * @return
     */
    private static String getSignContent(Map<String, String> sortedParams) {
        StringBuilder content = new StringBuilder();
        List<String> keys = new ArrayList<String>(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;
        for (String key : keys) {
            String value = sortedParams.get(key);
            if (StringUtils.areNotEmpty(key, value)) {
                content.append(index == 0 ? "" : "&").append(key).append("=").append(value);
                index++;
            }
        }
        return content.toString();
    }


    public static void main(String[] args) throws Exception {
        KeyPair keyPair =  RSAUtils.getKeyPair();
        String gsPrivateKey = new String(org.apache.commons.codec.binary.Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
        String gsPublicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));

        KeyPair keyPair2 =  RSAUtils.getKeyPair();
        String ybPrivateKey = new String(org.apache.commons.codec.binary.Base64.encodeBase64(keyPair2.getPrivate().getEncoded()));
        String ybPublicKey = new String(Base64.encodeBase64(keyPair2.getPublic().getEncoded()));

        YueBaoRequest yueBaoRequest = new YueBaoRequest();
        yueBaoRequest.setAppId("1111");
        yueBaoRequest.setContent("我叫韩大刀  你猜我是谁");
        yueBaoRequest.setMethod("2222");
        yueBaoRequest.setRequestId("1111");
        yueBaoRequest.setTimestamp("1111");
        yueBaoRequest =  getSignYueBaoRequest(yueBaoRequest,ybPublicKey,gsPrivateKey);

        System.out.println(yueBaoRequest);
          validateRequest(yueBaoRequest,gsPublicKey,ybPrivateKey);


        YueBaoResponse yueBaoResponse  = YueBaoResponse.success(yueBaoRequest,"你是韩大刀");


        yueBaoResponse =  getSignYueBaoResponse(yueBaoResponse,gsPublicKey,ybPrivateKey);

        boolean flag2 =   validateYueBaoResponse(yueBaoResponse,ybPublicKey,gsPrivateKey);


        System.out.println(flag2);

    }


    /**
     * 获取需要请求的对象
     * @param yueBaoRequest
     * @param yb_publicKey
     * @param app_privateKey
     * @return
     */
    public static YueBaoRequest getSignYueBaoRequest(YueBaoRequest yueBaoRequest , String yb_publicKey ,String app_privateKey) throws Exception {
        //对请求内容加密
        String encryptionContent =  RSAUtils.encrypt(yueBaoRequest.getContent(),RSAUtils.getPublicKey(yb_publicKey));
        yueBaoRequest.setContent(encryptionContent);
        Map<String,String> requestMap =  buildRequestMap(yueBaoRequest);
        String signContent =  getSignContent(requestMap);
        String sign =  RSAUtils.sign(signContent,RSAUtils.getPrivateKey(app_privateKey));
        yueBaoRequest.setSign(sign);
        return yueBaoRequest;
    }


    /**
     * 对悦保应答进行加密
     * @param yueBaoResponse
     * @param app_publicKey
     * @param yb_privateKey
     * @return
     */
    public static YueBaoResponse getSignYueBaoResponse(YueBaoResponse yueBaoResponse,String app_publicKey ,String yb_privateKey ) throws Exception {
        //对请求内容加密
        String encryptionContent =  RSAUtils.encrypt(yueBaoResponse.getContent(),RSAUtils.getPublicKey(app_publicKey));
        yueBaoResponse.setContent(encryptionContent);
        Map<String,String> requestMap =  buildResponseMap(yueBaoResponse);
        String signContent =  getSignContent(requestMap);
        String sign =  RSAUtils.sign(signContent,RSAUtils.getPrivateKey(yb_privateKey));
        yueBaoResponse.setSign(sign);
        return yueBaoResponse;
    }


    /**
     * 校验加密对悦保应答
     * @param yueBaoResponse
     * @param yb_publicKey
     * @param app_privateKey
     * @return
     */
    public static boolean validateYueBaoResponse(YueBaoResponse yueBaoResponse,String yb_publicKey ,String app_privateKey) throws Exception {
        Map<String,String> requestMap =  buildResponseMap(yueBaoResponse);
        String signContent =   getSignContent(requestMap);
        boolean flag =  RSAUtils.verify(signContent,RSAUtils.getPublicKey(yb_publicKey),yueBaoResponse.getSign());
        String responseContent =  RSAUtils.decrypt( yueBaoResponse.getContent(),RSAUtils.getPrivateKey(app_privateKey));
        yueBaoResponse.setContent(responseContent);
        return flag;
    }

    /**
     * 验证签名
     * @param yueBaoRequest
     * @param publicKey
     * @param privateKey
     * @return
     */
    public static boolean validateRequest(YueBaoRequest yueBaoRequest, String publicKey  , String privateKey) throws Exception {
        Map<String,String> requestMap =  buildRequestMap(yueBaoRequest);
        String signContent =   getSignContent(requestMap);
        boolean flag =  RSAUtils.verify(signContent,RSAUtils.getPublicKey(publicKey),yueBaoRequest.getSign());
        String requestContent =  RSAUtils.decrypt( yueBaoRequest.getContent(),RSAUtils.getPrivateKey(privateKey));
        yueBaoRequest.setContent(requestContent);
        return flag;
    }

    /**
     * 创建请求对象map
     * @param yueBaoRequest
     * @return
     */
    private static Map<String,String> buildRequestMap(YueBaoRequest yueBaoRequest){
        Map<String,String> requestMap = new TreeMap<String, String>();
        requestMap.put("appId",yueBaoRequest.getAppId());
        requestMap.put("method",yueBaoRequest.getMethod());
        requestMap.put("requestId",yueBaoRequest.getRequestId());
        requestMap.put("timestamp",yueBaoRequest.getTimestamp());
        requestMap.put("content",yueBaoRequest.getContent()) ;
        return requestMap;
    }


    /**
     * 创建返回对象map
     * @param yueBaoResponse
     * @return
     */
    private static Map<String,String> buildResponseMap(YueBaoResponse yueBaoResponse){
        Map<String,String> requestMap = new TreeMap<String, String>();
        requestMap.put("appId",yueBaoResponse.getAppId());
        requestMap.put("method",yueBaoResponse.getMethod());
        requestMap.put("requestId",yueBaoResponse.getRequestId());
        requestMap.put("timestamp",yueBaoResponse.getTimestamp());
        requestMap.put("message",yueBaoResponse.getMessage());
        requestMap.put("code",yueBaoResponse.getCode());
        return requestMap;
    }








}
